package com.xiaobao.utils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Aspect
@Configuration
@EnableTransactionManagement
public class GlobalTransactionAndCacheConfig {

    private static final Logger log = LoggerFactory.getLogger(GlobalTransactionAndCacheConfig.class);
    private final RedisTemplate<String, Object> redisTemplate;

    public GlobalTransactionAndCacheConfig(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 定义切点：匹配 Service 层的增删改方法
    @Pointcut("execution(* com.xiaobao.service..*.add*(..)) || " +
            "execution(* com.xiaobao.service..*.insert*(..)) || " +
            "execution(* com.xiaobao.service..*.update*(..)) || " +
            "execution(* com.xiaobao.service..*.delete*(..))||" +
            "execution(* com.xiaobao.service..*.get*(..))")
    public void writeMethods() {
    }

    // 在写操作成功后清除缓存
    @AfterReturning(pointcut = "writeMethods()")
    public void clearCacheAfterWrite(JoinPoint joinPoint) {
        try {
            // 获取方法签名
            String methodName = joinPoint.getSignature().getName();
            String className = joinPoint.getTarget().getClass().getName();

            // 根据方法名决定清除哪些缓存
            if (methodName.startsWith("save") || methodName.startsWith("insert") ||
                    methodName.startsWith("update") || methodName.startsWith("delete")) {

                // 获取实体类型（假设方法参数是实体类）
                Object[] args = joinPoint.getArgs();
                if (args.length > 0 && args[0] != null) {
                    Class<?> entityClass = args[0].getClass();

                    // 清除该实体相关的所有缓存
                    String cacheKeyPattern = "com.xiaobao.mapper." +
                            entityClass.getSimpleName() + "Mapper.*";
                    clearCacheByPattern(cacheKeyPattern);
                }
            }
        } catch (Exception e) {
            // 记录日志但不影响业务逻辑
            log.info("清除缓存失败: {}", e.getMessage());
        }
    }

    private void clearCacheByPattern(String pattern) {
        redisTemplate.keys(pattern).forEach(key -> {
            System.out.println("清除缓存: " + key);
            redisTemplate.delete(key);
        });
    }

}